// 动态发布和管理功能
document.addEventListener('DOMContentLoaded', () => {
    const postsList = document.getElementById('posts-list');
    const newPostForm = document.getElementById('new-post');
    const postContent = document.getElementById('post-content');
    const postMedia = document.getElementById('post-media');
  
    // 加载动态列表
    const loadPosts = async () => {
      try {
        const token = localStorage.getItem('token');
        const response = await fetch('/api/posts', {
          headers: {
            'Authorization': `Bearer ${token}`,
          },
        });
        const posts = await response.json();
        if (response.ok) {
          postsList.innerHTML = '';
          posts.forEach(post => {
            const postElement = document.createElement('div');
            postElement.className = 'post';
            postElement.innerHTML = `
              <div class="post-header">
                <h3>${post.author.profile.name}</h3>
                <small>${new Date(post.createdAt).toLocaleString()}</small>
              </div>
              <div class="post-content">${post.content}</div>
              <div class="post-media">
                ${post.media.map(media => `<img src="${media}" alt="Post media">`).join('')}
              </div>
              <div class="post-actions">
                <button class="like-btn" data-id="${post._id}">Like (${post.likes.length})</button>
                <button class="comment-btn" data-id="${post._id}">Comment</button>
              </div>
              <div class="post-comments">
                ${post.comments.map(comment => `
                  <div class="comment">
                    <small>${comment.author.profile.name}:</small>
                    <p>${comment.text}</p>
                  </div>
                `).join('')}
              </div>
            `;
            postsList.appendChild(postElement);
          });
  
          // 添加点赞事件监听
          document.querySelectorAll('.like-btn').forEach(btn => {
            btn.addEventListener('click', async () => {
              const postId = btn.getAttribute('data-id');
              try {
                const token = localStorage.getItem('token');
                const response = await fetch(`/api/posts/${postId}/like`, {
                  method: 'POST',
                  headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json',
                  },
                });
                if (response.ok) {
                  loadPosts();
                }
              } catch (error) {
                console.error('Failed to like post:', error);
              }
            });
          });
  
          // 添加评论事件监听
          document.querySelectorAll('.comment-btn').forEach(btn => {
            btn.addEventListener('click', async () => {
              const postId = btn.getAttribute('data-id');
              const commentText = prompt('Enter your comment:');
              if (commentText) {
                try {
                  const token = localStorage.getItem('token');
                  const response = await fetch(`/api/posts/${postId}/comment`, {
                    method: 'POST',
                    headers: {
                      'Authorization': `Bearer ${token}`,
                      'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ text: commentText }),
                  });
                  if (response.ok) {
                    loadPosts();
                  }
                } catch (error) {
                  console.error('Failed to comment on post:', error);
                }
              }
            });
          });
        }
      } catch (error) {
        console.error('Failed to load posts:', error);
      }
    };
  
    // 发布新动态
    newPostForm.addEventListener('submit', async (e) => {
      e.preventDefault();
      const content = postContent.value;
      const media = Array.from(postMedia.files).map(file => URL.createObjectURL(file));
  
      try {
        const token = localStorage.getItem('token');
        const response = await fetch('/api/posts', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ content, media }),
        });
        if (response.ok) {
          postContent.value = '';
          postMedia.value = '';
          loadPosts();
        }
      } catch (error) {
        console.error('Failed to create post:', error);
        alert('Failed to create post. Please try again.');
      }
    });
  });